<template>
  <div>
    <div :class="{'is-mobile':showMobilePage}" class="suspend-btn" @click="isShowProcess = true">
      <i class="el-icon-arrow-left icon"/>
      <div class="text">
        <div style="margin-bottom: 3px;">审批</div>
        <div>流程</div>
      </div>
    </div>
    <!-- 流程弹窗 -->
    <el-drawer
      :visible.sync="isShowProcess"
      :with-header="false"
      :append-to-body="appendToBody"
      :size="'34%'"
      custom-class="process-drawer process-drawer-bg">
      <div>
        <div class="progress-type-box">
          <div :class="progressType === 0 ? 'active' : ''" class="progress-type-btn" @click="progressType = 0">审批日志</div>
          <div :class="progressType === 1 ? 'active' : ''" class="progress-type-btn" @click="progressType = 1">审批进度</div>
          <div v-if="canReadRecord" :class="progressType === 2 ? 'active' : ''" class="progress-type-btn" @click="progressType = 2">修改记录</div>
        </div>
        <div :class="{'process-content-box':progressType !== 2}">
          <auditProcess
            v-loading="listLoading"
            v-if="progressType === 0"
            :process-status="processData.processStatus"
            :list="processCollectionComputed"
            :comment-status="commentStatus"
            :all-approver="allApprover"
            :is-creator="isRealCreator"
            :approval-module-type="approvalModuleType"
            :action-permissions="actionPermissions"
            :main-id="mainId"
            @onCommentStatusChange="onCommentStatusChange"
            @showCommentDialog="showCommentDialog"
            @onReplyComment="onReplyComment"
            @reloadComment="getProcessList" />
          <AuditProgressWrap
            v-else-if="progressType === 1"
            :flow-structure="auditScheduleData"
            :default-aduitor-list="defaultAduitorList"
            :operate-data="processData.operation"
            :process-data="auditScheduleData"
            :process-status="processData.processStatus"
            :has-press-auth="hasPressAuth"
            :senders="senders"
            :redirect-url="redirectUrl"
            @pressSendMsg="pressSendMsg"
            @addSigner="addSigner"
          />
          <recordList v-else-if="progressType === 2" ref="recordList" :id="moduleId? mainId : processId" :type="moduleId? 1 : 0" @getHistoryDetail="getHistoryDetail" @setCurrentVersion="setCurrentVersion" @freshDetail="freshDetail"/>
          <empty-placeholder v-else style="height: 400px;" />
        </div>
      </div>
    </el-drawer>
    <!-- 人员交接 -->
    <ApproverChange
      ref="approverChangeDialog"
      :business-type="businessType"
      :ids="mainId"
      :has-approver-change="actionPermissions.hasApproverChange"
      :module-id="moduleId"
      :append-to-body="appendToBody"
      @changeCallBack="approverChangeCallback"
    />
    <DiversAuditorDialog ref="auditorDialog" :can-empty="false" @userSelect="submitDeliverTo" @handleSender="handleSender"/>
    <CommentDialog
      ref="commentDialogRef"
      :comments-id="mainId"
      :append-to-body="appendToBody"
      :add-comment-api="commentAddApi"
      @sendCallback="commentSendCallback"
    />
    <auditDialog
      ref="auditDialog"
      :loading="auditLoading"
      :type="type"
      :operate-data="processData.operation"
      :default-aduitor-list="defaultAduitorList"
      :default-auth-user-list="defaultAuthUserList"
      :create-user="createUser"
      :dialog-form-visible="auditDialogVisible"
      :content="processData.operation.content"
      :audit-schedule-data="auditScheduleData"
      @close="closeDialog"
      @handleSubmit="handleSubmit"/>
    <processOperation
      :is-current-version="isCurrentVersion || Boolean(moduleId)"
      :disabled="disabled"
      :operate-data="processData.operation"
      :comment-total="commentCount"
      :show-comment-btn="true"
      :process-status="processData.processStatus"
      :process-data-list="processData.list"
      :is-create="isCreate"
      :can-create-auth="canCreateAuth"
      :flow-structure="auditScheduleData"
      :type="processType"
      :created-contract="false"
      :module-id="moduleId"
      :action-permissions="actionPermissions"
      :is-apply="isApply"
      :hide-press-btn="hidePressBtn"
      :show-print-btn="showPrint"
      :show-renewal-contract="showRenewalContract"
      :show-contract-create-btn="showContractCreateBtn"
      :show-resource-syncbtn="showResourceSyncbtn"
      :hidden-change-approval="hiddenChangeApproval"
      :show-resource-btn="showResourceBtn"
      @handleRefreshResource="handleRefreshResource"
      @handleEditResource="handleEditResource"
      @handleSendMsg="handleSendMsg"
      @handleRevocation="handleRevocation"
      @handleRecall="handleRecall"
      @handleAudit="handleAudit"
      @handleReapply="handleReapply"
      @handleRemodify="handleRemodify"
      @handleAddSigner="handleAddSigner"
      @deliverTo="deliverTo"
      @toBack="toBack"
      @showCommentDialog="showCommentDialog"
      @handleHigherRecall="handleHigherRecall"
      @handleResubmit="handleResubmit"
      @handleApproverChange="handleApproverChange"
      @handlePressSend="handlePressSend"
      @handleCancelPress="handleCancelPress"
      @handleCreateNew="handleCreateNew"
      @handleModify="handleModify"
      @handleToggleProcess="handleToggleProcess"
      @handleContractCreate="handleContractCreate"
      @handleSignUpSync="handleSignUpSync"
      @handleComment="showCommentDialog"
      @handlePrint="handlePrint"
      @handleCloseProcess="handleCloseProcess"
    >
      <PrintComponent v-if="showPrint && !showMobilePage && isCurrentVersion" v-show="false" ref="printRef" :approval-module-print-config="approvalModulePrintConfig" :process-id="processId" :print-data="printData" :process-type="processType" />
      <slot />
      <div v-if="$slots.pager" slot="pager">
        <slot name="pager"/>
      </div>
      <div v-if="$slots.signUp" slot="signUp">
        <slot name="signUp"/>
      </div>
      <div v-if="$slots.upOnline" slot="upOnline">
        <slot name="upOnline"/>
      </div>
    </processOperation>
  </div>
</template>

<script>
/**
 * 整合详情页审批流程，在审批流程中引用即可
 * 所有参数均必填
 */
// components
import auditProcess from '@/components/AuditProcess/index';
import AuditProgressWrap from '@/components/Common/auditProcess/auditProgress';
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
import auditDialog from '@/components/AuditProcess/auditDialog';
import ApproverChange from '@/components/Common/auditProcess/approverChange';
import processOperation from '@/components/AuditProcess/processOperation';
import CommentDialog from '@/components/Common/commentDialog';
import PrintComponent from '@/components/Common/print';
import RecordList from '@/components/Common/auditProcess/recordList';
// import { closeProcess } from '@/api/process';
// 数据
import { COMMENT_STATUS } from '@/utils/const/process';
import { COMMENT_RECORDREAD_PERMISSION_OF_MODULE } from '@/utils/const';
// util
import { mapState } from 'vuex';
import { MessageBox } from 'element-ui';
import { showModal } from '@/utils/message';
import { PROCESS_TYPE } from '@/utils/const/process';
import { hasRouteAuth } from '@/utils/permission';
// API
import {
  getProcessList, // 获取流程数据
  getApproveLatestInfo,
  contractHigherRecall,
  sumbDeliverTo,
  contractResubmit,
  scheduleCounterSign,
  pressSendMsg,
  getToggleInfo
} from '@/api/legal';
import { checkFieldLog } from '@/api/approvalModule';
import commentDel from '@/mixins/commentDel';
import filterObjStoreMixin from '@/mixins/filterObjStore';
import setProcessLog from '@/mixins/setProcessLog';
import { getCommonApprovalPermissions } from '@/api/approvalModule';
import ElMessage from '@/utils/message';

export default {
  name: 'ExamineAndApprove',
  components: {
    RecordList,
    AuditProgressWrap,
    processOperation,
    auditProcess,
    CommentDialog,
    auditDialog,
    DiversAuditorDialog,
    ApproverChange,
    PrintComponent
  },
  mixins: [commentDel, filterObjStoreMixin, setProcessLog],
  props: {
    mainId: { // 详情ID
      type: Number | String,
      default: ''
    },
    moduleId: { // 流程模块ID，如果有传说明是自定义审批
      type: Number | String,
      default: ''
    },
    processId: { // 流程ID
      type: Number | String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    redirectUrl: { // 通知跳转地址
      type: String,
      default: ''
    },
    createUser: { // 创建人
      type: Object,
      default: () => ({})
    },
    businessType: { // 审批人变更业务类型
      type: Number,
      default: 0
    },
    processType: { // 审批底部按钮类型
      type: Number,
      default: 0
    },
    commentAddApi: { // 添加评论的API
      type: Function,
      default: null
    },
    getCommentsApi: { // 获取评论的API
      type: Function,
      default: null
    },
    processRevocationApi: { // 撤销API
      type: Function,
      default: null
    },
    processRecallApi: { // 撤回API
      type: Function,
      default: null
    },
    processAuditApi: { // 流程审批API
      type: Function,
      default: null
    },
    editPageRouterName: { // 编辑页的路由名称
      type: String,
      default: 'editInvoiceAbandon'
    },
    detailPageRouterName: { // 详情页的路由名称
      type: String,
      default: 'invoiceAbandonDetail'
    },
    auditScheduleData: {
      type: Array | Object,
      default: null
    },
    senders: {
      type: Array,
      default: () => {
        return [];
      }
    },
    showResourceBtn: {
      type: Boolean,
      default: false
    },
    defaultAduitorList: { // 申请人
      type: Array,
      default: () => ([this.createUser])
    },
    nextApproveModuleId: { // 下一个审批详情接收的id名
      type: String,
      default: 'id'
    },
    showPrint: { // 是否开启打印
      type: Boolean,
      default: false
    },
    printData: { // 打印数据
      type: Object | Array,
      default: null
    },
    approvalModulePrintConfig: { // 自定义审批的打印配置
      type: Object,
      default: null
    },
    submitEventEdit: {
      type: Function,
      default: null
    },
    isCreatorPermission: {// 发起人权限
      type: Boolean,
      default: false
    },
    approvalModuleType: { // 模块对应类型
      type: Number,
      default: null
    },
    version: { // 详情版本
      type: Number | String,
      default: ''
    },
    isApply: { // 是否为申请人
      type: Boolean,
      default: false
    },
    showRenewalContract: { // 签约内审-关联签约合同
      type: Boolean,
      default: false
    },
    showContractCreateBtn: { // 达人解约-发起合同审批
      type: Boolean,
      default: false
    },
    canCreateAuth: { // 是否有新建权限，只有自定义审批才会传，因为自定义审批的权限是动态的
      type: Boolean,
      default: false
    },
    defaultAuthUserList: { // 授权人
      type: Array,
      default: () => {
        return [];
      }
    },
    hidePressBtn: {
      type: Boolean,
      default: false
    },
    showSignUpSlot: {
      type: Boolean,
      default: false
    },
    showResourceSyncbtn: {
      type: Boolean,
      default: true
    },
    requiredKeys: {
      type: Array,
      default: () => []
    },
    validateList: {
      type: Array,
      default: () => []
    },
    formValidate: {
      type: Function,
      default: null
    },
    appendToBody: {
      type: Boolean,
      default: false
    },
    hiddenChangeApproval: {
      type: Boolean,
      default: false
    },
    inListDrawer: {
      type: Boolean,
      default: false
    },
    isUpOnline: { // 是否为达人上刊
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      commentCount: 0,
      isShowProcess: false,
      type: null, // 0：拒绝 1：同意
      progressType: 0, // 0审批日志，1审批进度
      auditLoading: false,
      auditDialogVisible: false,
      processData: {// 流程信息
        list: [],
        operation: {
          auth: [],
          content: null
        }
      },
      operationSetEvents: [],
      listLoading: false,
      commentStatus: COMMENT_STATUS.SHOW_ALL,
      commentList: [], // 评论列表
      processCollectionList: [], // 评论和日志排序后的合集
      actionPermissions: {}, // 自定义表单页面操作权限
      isCurrentVersion: true, // 是否是当前版本
      checkLog: [] // 查看脱敏字段的日志
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isCreate() { // 创建人 + 创建人权限
      return this.isRealCreator || this.isCreatorPermission;
    },
    isRealCreator() { // 创建人
      return this.userInfo.id === this.createUser.id;
    },
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    toggleKeyName() {
      return this.$route.name + '_toggleKey';
    },
    sessionCacheKey() {
      return sessionStorage.getItem(this.toggleKeyName) || null;
    },
    // 是创建者或管理员
    hasPressAuth() {
      return this.isAdmin || this.isCreate;
    },
    getContinueApproveStatus() {
      const continueApproveLocalKey = 'CONTINUE_APPROVE_' + this.userInfo.id;
      const getApproveLocalStatus = window.localStorage.getItem(continueApproveLocalKey);
      return ![null, 'false'].includes(getApproveLocalStatus);
    },
    isExamine() { // 当前用户是否是当前节点审批人
      const processList = this.processData.list;
      if (!processList || processList.length === 0) return false;
      let item = null;
      processList.forEach(i => {
        // nodeStatus 节点状态： 0：结束 1：进行中 2：未审批
        if (!item && i.nodeStatus === 1) {
          item = i;
        }
      });
      if (!item || item.length === 0) return false;
      let userList = [];
      item.items.forEach(i => {
        userList = userList.concat(i.users);
      });
      return userList.some(i => {
        return i.id === this.userInfo.id;
      });
    },
    // 是否展示修改记录
    canReadRecord() {
      if (this.approvalModuleType || this.approvalModuleType === 0) {
        if (this.approvalModuleType === -1) { // 自定义表单
          return !!this.actionPermissions.hasRecordRead;
        } else {
          const permission = COMMENT_RECORDREAD_PERMISSION_OF_MODULE[this.approvalModuleType];
          return permission ? hasRouteAuth(permission) : false;
        }
      } else {
        return false;
      }
    },
    processCollectionComputed() { // 审批日志
      // 仅展示评论
      if (this.commentStatus === COMMENT_STATUS.SHOW_COMMENT) return this.processCollectionList;
      if (this.checkLog && this.checkLog.length) {
        const collectionList = this.processCollectionList.concat(this.checkLog);
        const processCollectionList = collectionList.sort((a, b) => {
          // nodeStatus 节点状态： 0：结束 1：进行中 2：未审批, -1: 评论 -2:查看字段
          let aTime, bTime;
          if (a.nodeStatus === -2) {
            aTime = a.time;
          } else {
            aTime = a.items.every(subItem => subItem.time) ? a.items[0].time : a.nodeStatus === 1 ? 9999999999999 : a.items[0].time;
          }
          if (b.nodeStatus === -2) {
            bTime = b.time;
          } else {
            bTime = b.items.every(subItem => subItem.time) ? b.items[0].time : b.nodeStatus === 1 ? 9999999999999 : b.items[0].time;
          }
          return bTime - aTime;
        });
        return processCollectionList;
      }
      return this.processCollectionList;
    }
  },
  watch: {
    progressType(val) {
      val === 1 && this.getAuditSchedule();
    }
  },
  created() {
    if (this.processType === PROCESS_TYPE.APPROVAL) {
      this.queryPermissions();
    }
  },
  mounted() {
    if (this.$route.query.openComment) {
      this.isShowProcess = true;
    }
    this.getCheckFieldLog();
  },
  methods: {
    // 自定义流程-设置页面操作对应权限
    queryPermissions() {
      if (!this.processId) return;
      getCommonApprovalPermissions(this.processId).then(res => {
        if (res.code === 200) {
          this.actionPermissions = res.data;
        }
      });
    },
    handlePressSend() {
      this.$emit('handlePressSend');
    },
    handleCancelPress() {
      this.$emit('handleCancelPress');
    },
    // 流程数据
    queryProcessData() {
      this.$emit('freshCardData');
      this.$emit('queryProcessData');
    },
    async getProcessList() {
      if (!this.processId && this.processId !== 0) return;
      try {
        this.listLoading = true;
        this.commentList = [];
        if (this.commentStatus !== COMMENT_STATUS.SHOW_COMMENT) {
          const processResult = await getProcessList({ id: this.processId });
          this.processData = processResult.data;
          this.$emit('setProcessData', this.processData);
          this.operationSetEvents = this.processData.operation.setEvents;
        }
        try {
          if (this.commentStatus !== COMMENT_STATUS.HIDE_COMMENT) {
            const commentParams = Object.create(null);
            commentParams.id = this.mainId;
            commentParams.page = 1;
            commentParams.perPage = 0;
            const commentResult = await this.getCommentsApi(commentParams);
            if (commentResult.data) {
              this.commentList = commentResult.data;
              this.commentCount = commentResult.count;
            }
          }
        } finally {
          const processList = this.commentStatus !== COMMENT_STATUS.SHOW_COMMENT ? _.cloneDeep(this.processData.list) : [];
          this.$nextTick(() => {
            this.processCollectionList = this.setProcessList(processList);
          });
          this.listLoading = false;
        }
      } catch (error) {
        console.log(error);
        this.listLoading = false;
      }
    },
    getAuditSchedule() {
      this.$emit('getAuditSchedule');
    },
    // 催办通知回调
    async pressSendMsg(data) {
      data.url = `${data.url}?${this.nextApproveModuleId}=${this.mainId}&processId=${this.processId}`;
      try {
        const { code } = await pressSendMsg(data);
        if (code === 200) { // 成功
          this.$emit('queryProcessData');
        }
      } catch (error) {
        console.error(error);
      }
    },
    // 选择完加签人的逻辑
    addSigner(data) {
      const param = {
        id: this.processId,
        examineRoles: [data]
      };
      scheduleCounterSign(param).then(res => {
        if (res.code === 200) {
          this.getAuditSchedule();
          this.getProcessList();
        }
      });
    },
    // 审批
    approverChangeCallback() {
      this.queryProcessData();
    },
    submitDeliverTo(data) {
      if (!data.selectUser || data.selectUser.length === 0) {
        this.$message.warning('请选择转交人');
        return;
      }
      const params = {
        id: this.processId,
        type: 2, // 2：审批转交
        deliver: data.selectUser[0].id,
        examineRoleId: this.processData.operation.examineRoleId
      };
      sumbDeliverTo(params).then(res => {
        if (res.code === 200) {
          this.$message.success('转交成功');
          this.queryProcessData();
        }
      });
    },
    onCommentStatusChange(status) {
      this.commentStatus = status;
      this.getProcessList();
    },
    showCommentDialog() {
      this.$refs['commentDialogRef'].dialogVisible = true;
    },
    onReplyComment(commentData) {
      this.$refs['commentDialogRef'].dialogVisible = true;
      this.$refs['commentDialogRef'].handleReply(commentData);
    },
    commentSendCallback() {
      this.getProcessList();
      this.progressType = 0;
      this.isShowProcess = true;
    },
    // 按钮操作
    // 撤销
    handleRevocation() {
      const params = { id: this.processId };
      this.processRevocationApi(params).then(res => {
        if (res.code === 200) {
          ElMessage.success('作废成功');
          this.queryProcessData();
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        ElMessage.error(err.message);
      });
    },
    // 撤回
    handleRecall(auth) {
      const h = this.$createElement;
      const recallAll = () => {
        MessageBox.close();
        this.handleRecallAll(false);
      };
      const recallPrev = () => {
        MessageBox.close();
        this.handleRecallPrev(false);
      };
      if (auth.includes(5) && auth.includes(3)) {
        MessageBox.confirm('', '', {
          message: h('p', null, [
            h('div', null, '请确认撤回至哪个步骤'),
            h('div', { class: 'btns-container' }, [
              h('el-button', { on: { click: recallAll }, class: '', props: { type: 'primary' }}, '撤回至任务发起'),
              h('el-button', { on: { click: recallPrev }, class: '' }, '撤回至上一步'),
              h('el-button', { on: { click: MessageBox.close }, class: 'cancel-btn' }, '返回')
            ])
          ]),
          confirmButtonText: '',
          cancelButtonText: '',
          showClose: false,
          showCancelButton: false,
          showConfirmButton: false,
          type: 'warning',
          lockScroll: false,
          customClass: 'del-message del-message-cancel message-box-order',
          iconClass: 'del-icon',
          center: true
        });
      } else if (auth.includes(3)) {
        this.handleRecallPrev();
      } else {
        this.handleRecallAll();
      }
    },
    // 撤回上一步
    handleRecallPrev(confirm = true) {
      const params = { id: this.processId, type: 0 };
      if (confirm) {
        showModal('请确认是否撤回', '', {
          cancelButtonText: '返回',
          lockScroll: false,
          iconClass: 'del-icon'
        }).then(() => {
          this.handlePostRecall(params);
        });
      } else {
        this.handlePostRecall(params);
      }
    },
    // 撤回至发起
    handleRecallAll(confirm = true) {
      const params = {
        id: this.processId,
        type: 1
      };
      if (confirm) {
        showModal('请确认是否撤回', '', {
          confirmButtonText: '撤回至任务发起',
          cancelButtonText: '返回',
          customClass: 'del-message del-message-cancel inloive-abandon-message-btn-margin',
          lockScroll: false,
          iconClass: 'del-icon'
        }).then(() => {
          this.handlePostRecall(params);
        });
      } else {
        this.handlePostRecall(params);
      }
    },
    handlePostRecall(params) {
      this.processRecallApi(params).then(res => {
        if (res.code === 200) {
          this.$message.success('撤回成功');
          this.queryProcessData();
        } else {
          this.$message.closeAll();
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.$message.closeAll();
        this.$message.error(err.message);
      });
    },
    handleCloseProcess(params) {
      showModal('请确认是否结束流程', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'del-message del-message-cancel inloive-abandon-message-btn-margin',
        lockScroll: false,
        iconClass: 'del-icon'
      }).then(() => {
        this.handleRevocation();
      });
    },
    requiredEventValidate() {
      return new Promise(async(resolve, reject) => {
        if (!this.formValidate) {
          resolve(true);
        } else {
          const res = await this.formValidate();
          if (res) {
            resolve(res);
          } else {
            reject(res);
          }
        }
      });
    },
    // 审批
    async handleAudit(val) {
      this.requiredEventValidate().then(() => {
        this.type = val;
        this.auditDialogVisible = true;
      }).catch((err) => {
        this.$message.warning(err);
      });
    },
    // 重新申请
    handleReapply(params) {
      const h = this.$createElement;
      const toEdit = () => {
        if (this.moduleId) {
          this.$router.push({
            name: this.editPageRouterName,
            params: {
              id: this.moduleId
            },
            query: {
              id: this.mainId,
              reapplyId: this.processId
            }
          });
        } else {
          this.$router.push({
            name: this.editPageRouterName,
            params: {
              id: this.mainId
            },
            query: {
              reapplyId: this.processId
            }
          });
        }

        MessageBox.close();
      };
      const toDetail = () => {
        const routeUrl = this.$router.resolve({
          name: this.detailPageRouterName,
          query: {
            id: params.relatedId,
            processId: params.relatedProcessId
          }
        });
        MessageBox.close();
        window.open(routeUrl.href, '_blank');
      };
      if (params.relatedProcessId && params.relatedId) {
        MessageBox.confirm('', '', {
          message: h('p', null, [
            h('div', null, '已有重新申请的审批单，是否继续新建'),
            h('div', { class: 'btns-container' }, [
              h('el-button', { on: { click: toEdit }, class: 'resolve-btn', props: { type: 'primary' }}, '新建'),
              h('el-button', { on: { click: toDetail }, class: 'reject-btn' }, '查看'),
              h('el-button', { on: { click: MessageBox.close }, class: 'cancel-btn' }, '再想想')
            ])
          ]),
          confirmButtonText: '新建',
          cancelButtonText: '再想想',
          showClose: false,
          showCancelButton: false,
          showConfirmButton: false,
          type: 'warning',
          lockScroll: false,
          customClass: 'del-message del-message-cancel message-box-order',
          iconClass: 'del-icon',
          center: true
        });
      } else {
        // 首次重新申请
        toEdit();
      }
    },
    // 修改
    handleRemodify() {
      if (this.moduleId) {
        this.$router.push({
          name: this.editPageRouterName,
          params: {
            moduleId: this.moduleId
          },
          query: {
            id: this.mainId,
            remodifyId: this.processId
          }
        });
      } else if (this.isUpOnline) {
        this.$emit('handleRemodify');
      } else {
        const query = {
          remodifyId: this.processId
        };
        query[`${this.nextApproveModuleId}`] = this.mainId;
        this.$router.push({
          name: this.editPageRouterName,
          params: {
            id: this.mainId
          },
          query
        });
      }
    },
    handleAddSigner() {
      this.progressType = 1;
      this.isShowProcess = true;
    },
    // 转交选择-审批转交
    deliverTo(type) {
      this.$refs['auditorDialog'].dialogVisible = true;
      this.deliverToType = type;
      const title = '转交';
      this.$refs['auditorDialog'].initDeliverTo(1, title);
    },
    // 高级撤回
    handleHigherRecall() {
      showModal('当前审批任务已完成，撤回后最后一步需要重新审批，请谨慎操作').then(() => {
        contractHigherRecall({ id: this.processId }).then(_ => {
          this.$message.success('撤回成功');
          this.queryProcessData();
        });
      });
    },
    // 重新提交
    handleResubmit() {
      if (this.isUpOnline) {
        this.$emit('handleResubmit');
      } else {
        showModal('当前审批未过审，请确认无误后进行重新提交，提交后将重新开始审批，如有内容调整请修改后再提交').then(() => {
          contractResubmit({ id: this.processId }).then(_ => {
            this.$message.success('提交成功');
            this.queryProcessData();
          });
        });
      }
    },
    // 审批审批转交
    handleApproverChange() {
      this.$refs['approverChangeDialog'].dialogVisible = true;
    },
    toBack() {
      this.$emit('toBack');
    },
    closeDialog() {
      this.auditLoading = false;
      this.auditDialogVisible = false;
    },
    // 打印
    handlePrint() {
      this.$refs['printRef'].printTable();
    },
    // 审批
    async handleSubmit(type, data) {
      this.auditLoading = true;
      if (this.submitEventEdit) {
        try {
          await this.submitEventEdit(type);
        } catch (_) {
          this.auditDialogVisible = false;
          this.auditLoading = false;
          return;
        }
      }
      const params = Object.assign({
        id: this.processId,
        status: type,
        examineRoleId: this.processData.operation.examineRoleId
      }, data);
      this.processAuditApi(params).then(res => {
        if (res.code === 200) {
          this.$emit('successAudit');
          this.$message({ type: 'success', message: '提交成功' });
          this.closeDialog();
          this.getContinueApproveStatus ? this.continueNextApprove() : this.queryProcessData();
        } else {
          this.$message.closeAll();
          this.$message({ type: 'error', message: res.message });
        }
        this.auditLoading = false;
      }).catch(err => {
        this.auditLoading = false;
        this.$message.closeAll();
        this.$message({ type: 'error', message: err.message });
      });
    },
    // 切换审批单（除付款申请、合同审批外的固定审批和自定义审批）
    handleToggleProcess(toggleType, processType) {
      const idArr = ['energyId', 'signUpId', 'issueId', 'id', 'reimbursementId', 'originalId', 'terminationId'];
      let currentId;
      for (const key in this.$route.query) {
        if (idArr.includes(key)) {
          currentId = Number(this.$route.query[key]);
        }
      }
      const params = {
        toggleType,
        businessType: this.businessType,
        processId: Number(this.processId),
        filterData: this.getFilterObj(processType),
        currentId,
        cacheKey: this.sessionCacheKey || new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999)
      };
      getToggleInfo(params).then(res => {
        if (res.code === 200) {
          if (res.data.finished) {
            this.$message.warning(toggleType ? '已经是最后一条审批单了' : '已经是最新的审批单了');
            return;
          }
          if (res.data.cacheKey) {
            sessionStorage.setItem(this.toggleKeyName, res.data.cacheKey);
          }
          this.goNextApproveDetail && this.goNextApproveDetail(res.data);
        }
      }).catch(err => console.error(err.message));
    },
    // 继续下一个审批
    continueNextApprove() {
      const params = Object.create(null);
      params.businessType = this.businessType;
      params.processId = this.processId;
      params.filterData = this.getFilterObj(this.processType);
      getApproveLatestInfo(params).then(res => {
        if (res.data.finished) {
          this.queryProcessData();
          this.getContinueApproveStatus && this.$nextTick(() => {
            const message = this.getFinishedMessage(this.processType);
            this.$message.closeAll();
            this.$message.success(message);
          });
        } else {
          this.goNextApproveDetail(res.data);
        }
      });
    },
    // 跳转详情页发票作废审批
    goNextApproveDetail(data) {
      if (this.inListDrawer) {
        this.$emit('goNextApproveDetail', data);
        return;
      }
      const RN = Math.floor(Math.random() * 10000);
      const { fromTodo, fromList } = this.$route.query;
      const query = {
        RN,
        resetData: true,
        processId: data.processId,
        fromTodo,
        fromList
      };
      query[this.nextApproveModuleId || 'id'] = data.id;
      this.$router.push({
        name: this.detailPageRouterName,
        query
      });
    },
    handleEditResource() {
      this.$emit('handleEditResource');
    },
    handleRefreshResource() {
      this.$emit('handleRefreshResource');
    },
    handleCreateNew() {
      this.$emit('handleCreateNew');
    },
    openAuditorDialog() {
      this.$refs['auditorDialog'].initSelectSender();
    },
    handleSendMsg() {
      this.$emit('handleSendMsg');
    },
    handleSender(selectUser = []) {
      this.$emit('handleSender', selectUser);
    },
    handleModify() {
      this.$emit('handleModify');
    },
    // 达人解约-发起合同审批
    handleContractCreate() {
      this.$emit('handleContractCreate');
    },
    // 达人解约-账号资源同步
    handleSignUpSync() {
      this.$emit('handleSignUpSync');
    },
    getHistoryDetail(id) {
      this.$emit('getHistoryDetail', id, this.approvalModuleType);
    },
    setCurrentVersion(isCurrentVersion = true) {
      this.isCurrentVersion = isCurrentVersion;
      this.$emit('setCurrentVersion', isCurrentVersion);
    },
    // 更新版本记录
    toUpdateRecord() {
      this.$refs.recordList && this.$refs.recordList.getRecords();
    },
    // 更新详情
    freshDetail() {
      this.$emit('freshDetail');
    },
    getCheckFieldLog() {
      if (!this.processId && this.processId !== 0) return;
      checkFieldLog({ processId: this.processId }).then(res => {
        if (res.code === 200 && res.data) {
          res.data.forEach(i => {
            i.nodeStatus = -2;
            if (i.time.toString().length === 10) i.time = i.time * 1000;
          });
          this.checkLog = res.data;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.suspend-btn {
  position: fixed;
  right: 16px;
  top: 50%;
  z-index: 2001;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;;
  border-top-left-radius: 8px;
  border-bottom-left-radius: 8px;
  color: #fff;
  cursor: pointer;
  background: linear-gradient(163deg, #93ADFF 0%, #2754E2 100%);
  box-shadow: 0px 3px 7px rgba(39, 84, 226, 0.31);
  &.is-mobile {
    right: 0;
  }
  .icon {
    font-size: 16px;
    font-weight: 500;
  }
  .text {
    font-size: 12px;
  }
  .suspend-btn-img {
    width: 14px;
    height: 17px;
  }
}
.btns-container {
  margin-top: 20px;
}
.process-drawer {
  background-color: #fafbff;
}
.progress-type-box {
  display: flex;
  margin: 0 12px;
  border-bottom: 1px solid #E6EDFF;
  padding-top: 12px;
  .progress-type-btn {
    cursor: pointer;
    font-size: 16px;
    color: #333333;
    margin-right: 32px;
    padding-bottom: 5px;
    &.active {
      color: #406EFF;
      font-weight: bold;
      border-bottom: 2px solid #406EFF;
    }
  }
  .progress-type-btn:last-child {
    margin-right: 0px;
  }
}
.process-content-box {
  height: calc(100vh - 44px) ;
  padding: 4px 5px 0 12px;
  @include scrollBar();
}

::v-deep .process-operation {
  position: relative;
  display: flex;
  align-items: center;
}
::v-deep .el-drawer {
  min-width: 300px;
}
</style>
<style lang="scss">
.inloive-abandon-message-btn-margin  .el-message-box__btns .el-button--default:first-child {
  margin-right: -220px;
}
</style>
